import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'const.dart';
import 'game.dart';
import 'game_board.dart';
import 'l10n/app_localizations.dart';

// 主视图
class MainWidget extends StatefulWidget {
  const MainWidget({super.key});

  /// 创建状态。
  /// @return 状态
  @override
  State<StatefulWidget> createState() => _MainState();
}

// 主状态
class _MainState extends State<MainWidget> {
  Game? _mGame; // 游戏

  /// 界面布局。
  /// @return 视图
  @override
  Widget build(BuildContext context) {
    // 计算所有水平方向或垂直方向的线宽度尺寸之和（边框+所有内部的线）
    const allLineWidth = Const.gameBoardPenWidth * (Const.gameBoardGridCountH + 1);

    // 计算格的尺寸
    Const.gridSize = (MediaQuery.of(context).size.width - Const.gameBoardPadding) / Const.gameBoardGridCountH - allLineWidth;

    // 计算游戏区域的尺寸
    var gameBoardSize = Const.gridSize * Const.gameBoardGridCountH + allLineWidth;

    // 创建游戏
    _mGame ??= Game(this, gameBoardSize);

    // 多语言
    final al = AppLocalizations.of(context)!;

    // 吐司窗口
    if (_mGame!.status == Status.won) {
      Fluttertoast.showToast(msg: al.ids_won, toastLength: Toast.LENGTH_LONG);
    } else if (_mGame!.status == Status.lost) {
      Fluttertoast.showToast(msg: al.ids_lost, toastLength: Toast.LENGTH_LONG);
    }

    // 界面布局
    return GestureDetector(
      onHorizontalDragEnd: (dragEndDetails) {
        _mGame!.onFling(dragEndDetails);
      },
      onVerticalDragEnd: (dragEndDetails) {
        _mGame!.onFling(dragEndDetails);
      },
      child: Container(
        color: Colors.white,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            GameBoard(gameBoardSize, gameBoardSize, _mGame!.draw),
            SizedBox(
              width: gameBoardSize,
              child: Padding(
                padding: EdgeInsets.only(top: Const.gameBoardPadding),
                child: ElevatedButton(
                  onPressed: () {
                    _mGame!.start();
                  },
                  child: Text(_mGame!.status == Status.playing ? al.ids_restart: al.ids_start)
                )
              )
            )
          ]
        )
      )
    );
  }
}
